package com.woniuxy.service.impl;

import com.woniuxy.entity.po.stationPile.Station;
import com.woniuxy.entity.po.stationPile.StationSchedule;
import com.woniuxy.mapper.StationMapper;
import com.woniuxy.mapper.StationScheduleMapper;
import com.woniuxy.service.StationScheduleService;
import com.woniuxy.util.TimeCalculator;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@AllArgsConstructor
public class StationScheduleServiceImpl implements StationScheduleService {

    private final StationMapper stationMapper;
    private final StationScheduleMapper scheduleMapper;

    @Transactional
    public void checkAndUpdateStatus() {
        LocalDateTime now = LocalDateTime.now();

        // 1. 查询需要切换状态的充电站
        List<Station> stations = stationMapper.findByNextTimeBefore(now);
        if (stations == null || stations.isEmpty()) return;
        stations.forEach(station -> {
            // 2. 查询该充电站所有有效规则
            List<StationSchedule> schedules = scheduleMapper.findActiveSchedules(station.getId());

            // 3. 计算下次切换时间
            TimeCalculator.NextTimeResult result = TimeCalculator.calculateNextTime(station, schedules);

            // 4. 更新状态和时间
            boolean shouldEnable = now.isAfter(station.getNextStartTime());
            updateStationStatus(station, shouldEnable);
            station.setNextStartTime(result.getStart());
            station.setNextEndTime(result.getEnd());
        });

        // 5. 批量更新数据库
        stationMapper.batchUpdate(stations);
    }

    private void updateStationStatus(Station station, boolean enable) {
        station.setStationCondition(enable ? 2 : 1);
    }
}
